package com.android.webserver.security;

import java.net.MalformedURLException;
import java.net.URL;

import android.util.Log;

import com.android.webserver.manager.WebServerManager;
import com.android.webserver.tornado.Request;
import com.android.webserver.tornado.Response;

/**
 * @author Baptiste GOURDIN
 *
 */
public class Origin {
	static public boolean verifyRequest (Request request, Response response) {
		String url = request.getHeader("origin");
		if (url == null)
			url = request.getHeader("Referer");
		if (url != null) {
			String host = null;
			try {
				URL refURL = new URL(url);
				if (!refURL.getProtocol().equalsIgnoreCase("http") && !refURL.getProtocol().equalsIgnoreCase("https")) {
					Log.i("WebServer", "******* Bad Origin Header : protocol not http / https *******");
					return false;
				}
				
				host = refURL.getHost();
				if (host != null && (host.equalsIgnoreCase("localhost") || host.equalsIgnoreCase("127.0.0.1")))
					return true;

				String addr = WebServerManager.getLocalIpAddress();
				if (!host.equals(addr)) {
					Log.i("WebServer", "******* Bad Origin Header : Host (" + host + "not in the list *******");
					return false;
				}

			} catch (MalformedURLException e) {
				Log.i("WebServer", "******* Bad Origin Header : Malformed URL *******");
				return false;
			}
		}
		
		return true;
	}
}
